<?php defined('BASEPATH') OR die('No direct access allowed.');
/**
 * Description of Signup
 *
 * Created on Dec 21, 2010
 * @author Ramon Gutierrez
 * @copyright Bitstop Network Services Inc.
 * @version 0.1
 */
class Signup extends Controller {
	function Signup() {
		parent::Controller();
		global $header, $data;
		
		// Header variables
		$header['extras'] = "";
		$header['grid'] = false;
		$data['module'] = 'signup';
	}
	
	function index() {
		global $header, $data;
		
		// Load reCaptcha stuff
		$this->load->library('recaptcha');
		
		// Load up that header!
		$header['title'] = $this->lang->line('title_signup');
		if(!$this->session->userdata('account_id')) {
			$header['extras'] = '<script type="text/javascript" src="' . site_url('js/jquery.bpopup-0.4.1.min.js') . '"></script>' . "\n" .
								'<script type="text/javascript">' . "\n" .
								'// <![CDATA[' . "\n" .
								'  $(document).ready(function() {' . "\n" .
								'    var options = {' . "\n" .
								'        target:         "#response",' . "\n" .
								'        success:        showResponse' . "\n" .
								'    };' . "\n\n" .
								'    $("#view-tos").bind("click", function() {' . "\n" .
								'      $("#tos-div").bPopup({ content: "iframe", follow: false, loadUrl: $("#view-tos").attr("href") });' . "\n" .
								'      return false;' . "\n" .
								'    });' . "\n\n" .
								'    $("#theform").ajaxForm(options);' . "\n" .
								'    function showResponse(responseText, statusText) {' . "\n" .
								'      if(responseText) {' . "\n" .
								'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
								'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
								'        $("#response").html(responseText).show();' . "\n" .
								'        //alert(responseText);' . "\n" .
								'        Recaptcha.reload();' . "\n" .
								'        submitted = false;' . "\n" .
								'        $(".info").remove();' . "\n" .
								'        revalidate();' . "\n" .
								'      } else {' . "\n" .
								'        $("#response").hide();' . "\n" .
								'        alert("Registration successful!");' . "\n" .
								'        window.location = "' . site_url() . '";' . "\n" .
								'      }' . "\n" .
								'    };' . "\n" .
								'  });' . "\n" .
								'// ]]>' . "\n" .
								'</script>' . "\n\n";
		}
							
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Get XML geodata using remote API
		$api_key = "1965983bc9c77c1a11d29424350abc05891b6befe80470607eef9542c9914fcf";
		$ip_address = getIpAddress();
		$xmlfile = "http://api.ipinfodb.com/v2/ip_query.php?key=$api_key&ip=$ip_address&timezone=true";
		$xmlRaw = file_get_contents($xmlfile);
		$this->load->library('simplexml');
		$data['geodata'] = $this->simplexml->xml_parse($xmlRaw);
		
		// Retrieve additional data
		$data['industry_types'] = $this->common_model->getIndustryTypes();
		$data['countries'] = $this->common_model->getCountries();
		
		// Dish out the meat
		$data['captcha'] = $this->load->view('recaptcha', array('recaptcha'=>$this->recaptcha->get_html()), TRUE);
		$this->load->view('signup', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function ajax() {
		// Load reCaptcha stuff
		$this->load->library('recaptcha');
		
		// Load e-mail library
		$this->load->library('email');
		
		// Post variables
		$post['company_name'] = $this->input->post("company_name");
		$post['industry_type'] = $this->input->post("industry_type");
		$post['first_name'] = $this->input->post("first_name");
		$post['last_name'] = $this->input->post("last_name");
		$post['street_address'] = $this->input->post("street_address");
		$post['city'] = $this->input->post("city");
		$post['state'] = $this->input->post("state");
		$post['country_id'] = $this->input->post("country_id");
		$post['zip'] = $this->input->post("zip");
		$post['email'] = $this->input->post("email");
		$post['contact_number'] = $this->input->post("contact_number");
		$post['username'] = $this->input->post("acct_username");
		$post['password'] = $this->input->post("acct_password");
		$post['confirm'] = $this->input->post("acct_confirm");
		$post['tos'] = $this->input->post("tos");
		$error = false;
		
		// Check for duplicates
		$dupe_username = $this->db->select('id')->from('accounts')->where("username", $post['username'])->get();
		$dupe_email = $this->db->select('id')->from('accounts')->where("email", $post['email'])->get();
		
		// Check for errors
		$error .= !$post['company_name'] ? "<li>Provide a company name.</li>" : '';
		$error .= !$post['industry_type'] || !is_numeric($post['industry_type']) ? "<li>Select an industry type.</li>" : '';
		$error .= !$post['first_name'] ? "<li>Enter first name of contact person.</li>" : '';
		$error .= !$post['last_name'] ? "<li>Enter last name of contact person.</li>" : '';
		$error .= !$post['street_address'] ? "<li>Provide a street address.</li>" : '';
		$error .= !$post['city'] ? "<li>Provide a city name.</li>" : '';
		$error .= !$post['state'] ? "<li>Provide a state or province.</li>" : '';
		$error .= !$post['country_id'] || !is_numeric($post['country_id']) ? "<li>Select a country.</li>" : '';
		$error .= !$post['email'] || !validate_email($post['email']) ? "<li>Provide a valid e-mail address.</li>" : ($dupe_email->num_rows() > 0 ? "<li>E-mail address is already in use.</li>" : '');
		$error .= !$post['contact_number'] ? "<li>Enter a contact number for this company.</li>" : '';
		$error .= !$post['username'] || strlen($post['username']) < 5 ? "<li>Username must have at least 5 characters.</li>" : ($dupe_username->num_rows() > 0 ? "<li>Username is already taken.</li>" : '');
		$error .= !$post['password'] || strlen($post['password']) < 7 ? "<li>Password must have at least 7 characters.</li>" : '';
		$error .= $post['confirm'] != $post['password'] ? "<li>Password and confirmation fields must match.</li>" : '';
		$error .= !$this->recaptcha->check_answer($_SERVER["REMOTE_ADDR"], $this->input->post('recaptcha_challenge_field'), $this->input->post('recaptcha_response_field')) ? "<li>Wrong validation code entered</li>" : "";
		$error .= !$post['tos'] ? "<li>You must agree to the terms and conditions.</li>" : '';
		
		if(!$error) {
			$data = array(
						  'last_name' => $post['last_name'],
						  'first_name' => $post['first_name'],
						  'street_address' => $post['street_address'],
						  'city' => $post['city'],
						  'state' => $post['state'],
						  'country_id' => $post['country_id'],
						  'zip' => $post['zip'],
						  'email' => $post['email'],
						  'contact_number' => $post['contact_number'],
						  'username' => $post['username'],
						  'password' => md5($post['password']),
						  'account_type' => 'company'
						 );

			$query1 = $this->common_model->create('accounts', $data);
			$query2 = false;
			
			if($query1) {
				// Generate unique validation key
				$validation_key = $this->common_model->create_validation();
				
				$data = array(
							  'name' => $post['company_name'],
							  'industry_type' => $post['industry_type'],
							  'validation_key' => $validation_key,
							  'class_of_service' => '1',
							  'account_id' => $query1
							 );
				
				$query2 = $this->common_model->create('clients', $data);
			}
			
			if(!$query1 || !$query2) {
				$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			// Send confirmation e-mail
			$this->email->from('noreply@queue-systems.com', $this->lang->line('app_title'));
			$this->email->to($post['email']);
			$this->email->subject($this->lang->line('signup_email_subject'));
			$this->email->message($this->lang->line('signup_email_body_head') . "\r\n\r\n" .
								  $this->lang->line('signup_company_name') . ': ' . $post['company_name'] . "\r\n\r\n" .
								  $this->lang->line('username') . ': ' . $post['username'] . "\r\n" .
								  $this->lang->line('password') . ': ' . $post['password'] . "\r\n\r\n" .
								  $this->lang->line('signup_email_body_foot'));
			$this->email->send();
		}
	}
	
	// Ajax to check for duplicate values for unique columns
	function check() {
		$type = $this->input->post('type');
		$val = $this->input->post('val');
		
		$check = $this->db->select('id')->from('accounts')->where($type, $val)->get();
		
		if($check->num_rows() == 0) {
			echo 'true';
		}
	}
}

/* End of file signup.php */
/* Location: ./system/application/controllers/signup.php */